package com.etime.shycourse.orde.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etime.shycourse.config.Tools;
import com.etime.shycourse.dto.CurrentUser;
import com.etime.shycourse.orde.dao.BuycarMapper;
import com.etime.shycourse.orde.dto.BuyCarIncludeGoodsDto;
import com.etime.shycourse.orde.pojo.Buycar;
import com.etime.shycourse.orde.services.interfaces.BuycarServices;
import com.etime.shycourse.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author wb
 * @since 2022-01-12
 */
@Service
public class BuycarServiceImpl implements BuycarServices {
    @Autowired
    private BuycarMapper mapper;

    @Autowired
    private Tools tools;

    /**
     * 加入购物车数据
     * insetOrUpdateBuyCar
     *
     * @param buyCarList list 集合
     * @return 加入是购物车的id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insetOrUpdateBuyCar(List<Buycar> buyCarList, String token) {
        // token部位空  购物车的数据大于0
        if (token != null & buyCarList.size () > 0) {
            CurrentUser currentUser = tools.getCurrentUserFromRedis (token);
            // 用户信息不存在
            SysUser user = currentUser.getUser ();
            if (user == null) {
                return 0;
            }
            try {
                // 循环添加创建 购物车信息
                buyCarList.forEach (l -> {
                    Integer integer = mapper.selectCount (new QueryWrapper<Buycar> ().eq ("odcourseid", l.getOdcourseid ()).eq ("buycaruserid", user.getUserid ()));
                    // 购物车不存在 才进行添加
                    if (integer == 0) {
                        l.setBuycaruserid (user.getUserid ());
                        int insert = mapper.insert (l);
                        // 如果创建购物车失败抛出异常
                        if (insert == 0) {
                            try {
                                throw new Exception ("创建购物车信息失败！");
                            } catch (Exception e) {
                                e.printStackTrace ();
                            }
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace ();
                // @Transactional和try catch捕获异常会让注解失效
                TransactionAspectSupport.currentTransactionStatus ().setRollbackOnly ();
                return 0;
            }
            return 1;
        }
        return 0;
    }

    /**
     * 支招模块     * 加入购物车数据
     *
     * @param buyCarList
     * @param token
     * @return int
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insetSupportOrUpdateBuyCar(List<Buycar> buyCarList, String token) {
        // token部位空  购物车的数据大于0
        if (token != null & buyCarList.size () > 0) {
            CurrentUser currentUser = tools.getCurrentUserFromRedis (token);
            // 用户信息不存在
            SysUser user = currentUser.getUser ();
            if (user == null) {
                return 0;
            }
            try {
                // 循环添加创建 购物车信息
                buyCarList.forEach (l -> {
                    Integer integer = mapper.selectCount (new QueryWrapper<Buycar> ().eq ("odlessonid", l.getOdlessonid ()).eq ("buycaruserid", user.getUserid ()));
                    // 购物车不存在 才进行添加
                    if (integer == 0) {
                        l.setBuycaruserid (user.getUserid ());
                        int insert = mapper.insert (l);
                        // 如果创建购物车失败抛出异常
                        if (insert == 0) {
                            try {
                                throw new Exception ("创建购物车信息失败！");
                            } catch (Exception e) {
                                e.printStackTrace ();
                            }
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace ();
                // @Transactional和try catch捕获异常会让注解失效
                TransactionAspectSupport.currentTransactionStatus ().setRollbackOnly ();
                return 0;
            }
            return 1;
        }
        return 0;
    }

    /**
     * 查询购物车数据接口 buycaruserid
     *
     * @param token-->redis--> 用户id
     * @return BuyCarIncludeGoodsTypeDto 购物车包括 课程信息 Dto
     */
    @Deprecated
    @Override
    public List<BuyCarIncludeGoodsDto> selectBuyCarIncludeGoodsByUserId(String token) {
        CurrentUser currentUser = tools.getCurrentUserFromRedis (token);
        // 用户信息不存在
        SysUser user = currentUser.getUser ();
        if (user == null) {
            return null;
        }
        Integer userid = user.getUserid ();
        if (userid == null) {
            return null;
        }
        List<Buycar> buyCarList = this.selectOdGoodStyPeByUserId (userid);
        if (buyCarList.size () > 0) {
            List<BuyCarIncludeGoodsDto> list = new ArrayList<> ();
            buyCarList.forEach (l -> {
                BuyCarIncludeGoodsDto buyCarIncludeGoodsDto = mapper.selectBuyCarIncludeGoodsDtoById (l.getBuycarid (), l.getOdgoodstype ());
                list.add (buyCarIncludeGoodsDto);
            });
            return list;
        }
        return null;
    }

    @Override
    public List<BuyCarIncludeGoodsDto> selectBuyCarIncludeGoodsByUserIds(String token) {
        CurrentUser currentUser = tools.getCurrentUserFromRedis (token);
        // 用户信息不存在
        SysUser user = currentUser.getUser ();
        if (user == null) {
            return null;
        }
        Integer userid = user.getUserid ();
        if (userid == null) {
            return null;
        }
        return mapper.selectBuyCarIncludeGoodsByUserId (userid);
    }

    /**
     * deleteByUserId
     * 删除购物车中的信息 物理删除
     *
     * @param buyCarUserId 用户id
     * @return int 影响数据的条数 0 失败 1成功
     */
    @Override
    public int deleteByUserId(Integer buyCarUserId) {
        Map<String, Object> map = new HashMap<> ();
        map.put ("buycaruserid", buyCarUserId);
        return mapper.deleteByMap (map);
    }

    /**
     * 根据购物车id 查询购物车一条数据
     * 购物车的详细信息 课程 + 章节 + 课时
     *
     * @param buyCarId
     * @return Buycar
     */
    @Override
    public BuyCarIncludeGoodsDto selectBuyCarById(Integer buyCarId) {
        // 获取到 购物车商品类型 odgoodstype
        //      1--课程
        //      2--章
        //      3--节
        //      4--课时
        Buycar buycar = this.selectOdGoodStyPeById (buyCarId);
        return mapper.selectBuyCarIncludeGoodsDtoById (buyCarId, buycar.getOdgoodstype ());
    }

    /**
     * deleteByBuyCarId
     * 删除购物车中的信息 物理删除
     *
     * @param buyCarId 购物车id
     * @return int 影响数据的条数 0 失败 1成功
     */
    @Override
    public int deleteByBuyCarId(Integer buyCarId) {
        return mapper.deleteById (buyCarId);
    }

    /**
     * 根据购物车id 查询购物车 商品类型
     * odgoodstype说明：
     * 1--课程
     * 2--章
     * 3--节
     * 4--课时
     * selectBuyCarById
     *
     * @param buyCarId
     * @return odgoodstype 商品类型
     */
    @Override
    public Buycar selectOdGoodStyPeById(Integer buyCarId) {
        return mapper.selectOne (new QueryWrapper<Buycar> ().eq ("buycarid", buyCarId).select ("odgoodstype", "buycarid"));
    }

    /**
     * 根据购用户id 查询出购物车id 商品类型
     * odgoodstype说明：
     *
     * @param UserId
     * @return Buycar中的 buycarid  odgoodstype
     */
    @Override
    public List<Buycar> selectOdGoodStyPeByUserId(Integer UserId) {
        return mapper.selectList (new QueryWrapper<Buycar> ().eq ("buycaruserid", UserId).select ("odgoodstype", "buycarid"));
    }

    /**
     * 根据用户id 课程 判断是否加入购物车
     * <p></p>
     * 存在返回 1
     * 不存在返回 0
     *
     * @param courseID
     * @return Integer
     */
    @Override
    public Integer iFBuyCarCourse(Integer courseID, String token) {
        CurrentUser currentUser = tools.getCurrentUserFromRedis (token);
        if (currentUser == null) {
            return null;
        }
        // 用户信息不存在
        SysUser user = currentUser.getUser ();
        if (user == null) {
            return null;
        }
        // 为了前期测试 程序不报错 用list接收   上线后用 selectOne
        List<Buycar> buycar = mapper.selectList (new QueryWrapper<Buycar> ().select ("buycarid").eq ("odcourseid", courseID).eq ("buycaruserid", user.getUserid ()));
        // 存在返回 1 不存在返回 0
        return buycar.size () > 0 ? 1 : 0;
    }
}
